/**
 * 申请审核页面的JavaScript功能
 */

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查用户权限
    checkAdminPermission();
    
    // 初始化侧边栏
    initSidebar();
    
    // 初始化筛选功能
    initFilters();
    
    // 初始化搜索功能
    initSearch();
    
    // 初始化表格交互
    initTableActions();
    
    // 初始化分页功能
    initPagination();
});

/**
 * 检查用户是否有管理员权限
 */
function checkAdminPermission() {
    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null');
    
    // 如果用户未登录或不是管理员，重定向到登录页
    if (!userInfo || !userInfo.isAdmin) {
        window.utils.showNotification('您没有管理员权限，请使用管理员账号登录', 'error');
        setTimeout(() => {
            window.location.href = '../login.html';
        }, 2000);
    }
}

/**
 * 初始化侧边栏
 */
function initSidebar() {
    // 获取当前页面路径
    const currentPath = window.location.pathname.split('/').pop() || 'dashboard.html';
    
    // 设置当前页面的侧边栏项为激活状态
    const sidebarItems = document.querySelectorAll('.admin-sidebar-item');
    sidebarItems.forEach(item => {
        const link = item.querySelector('a');
        const linkPath = link.getAttribute('href');
        if (linkPath === currentPath) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
    
    // 获取用户信息并更新侧边栏用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null');
    if (userInfo) {
        const usernameElement = document.querySelector('.admin-username');
        if (usernameElement) {
            usernameElement.textContent = userInfo.username || '管理员';
        }
    }
}

/**
 * 初始化筛选功能
 */
function initFilters() {
    const filterSelects = document.querySelectorAll('.filter-select');
    filterSelects.forEach(select => {
        select.addEventListener('change', function() {
            // 执行筛选逻辑
            filterApplications();
        });
    });
}

/**
 * 根据筛选条件过滤申请列表
 */
function filterApplications() {
    // 获取筛选条件
    const statusFilter = document.querySelector('.filter-select:nth-child(1)').value;
    const timeFilter = document.querySelector('.filter-select:nth-child(2)').value;
    const demandFilter = document.querySelector('.filter-select:nth-child(3)').value;
    
    // 获取所有申请行
    const rows = document.querySelectorAll('.admin-table tbody tr');
    
    // 遍历每一行，根据筛选条件显示或隐藏
    rows.forEach(row => {
        const status = row.querySelector('.status-badge').textContent.trim();
        const date = row.querySelector('td:nth-child(4)').textContent.trim();
        const demand = row.querySelector('.application-demand').textContent.trim();
        
        // 判断是否符合筛选条件
        const matchStatus = statusFilter === '所有状态' || status === statusFilter.replace('待审核', '待审核').replace('已通过', '已通过').replace('已拒绝', '已拒绝');
        const matchTime = timeFilter === '所有时间' || matchTimeFilter(date, timeFilter);
        const matchDemand = demandFilter === '所有需求' || demand.includes(demandFilter);
        
        // 显示或隐藏行
        if (matchStatus && matchTime && matchDemand) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
    
    // 更新分页
    updatePagination();
}

/**
 * 判断日期是否符合时间筛选条件
 * @param {string} dateStr - 日期字符串
 * @param {string} filter - 筛选条件
 * @returns {boolean} 是否符合条件
 */
function matchTimeFilter(dateStr, filter) {
    const date = new Date(dateStr);
    const today = new Date();
    const now = new Date();
    
    // 设置今天的开始时间
    today.setHours(0, 0, 0, 0);
    
    // 根据筛选条件判断
    switch (filter) {
        case '今天':
            return date >= today;
        case '本周':
            const startOfWeek = new Date(now);
            startOfWeek.setDate(now.getDate() - now.getDay());
            startOfWeek.setHours(0, 0, 0, 0);
            return date >= startOfWeek;
        case '本月':
            const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
            return date >= startOfMonth;
        case '上个月':
            const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
            const endOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
            return date >= startOfLastMonth && date <= endOfLastMonth;
        default:
            return true;
    }
}

/**
 * 初始化搜索功能
 */
function initSearch() {
    const searchInput = document.getElementById('application-search-input');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const rows = document.querySelectorAll('.admin-table tbody tr');
            
            rows.forEach(row => {
                const userName = row.querySelector('.user-info span').textContent.toLowerCase();
                const demandTitle = row.querySelector('.application-title').textContent.toLowerCase();
                const demandInfo = row.querySelector('.application-demand').textContent.toLowerCase();
                
                // 如果搜索词匹配用户名或需求标题或需求信息，则显示该行
                if (userName.includes(searchTerm) || demandTitle.includes(searchTerm) || demandInfo.includes(searchTerm)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
            
            // 更新分页
            updatePagination();
        });
    }
}

/**
 * 初始化表格交互
 */
function initTableActions() {
    // 表格操作按钮事件
    const actionButtons = document.querySelectorAll('.btn-icon');
    actionButtons.forEach(button => {
        button.addEventListener('click', function() {
            const action = this.getAttribute('title');
            const row = this.closest('tr');
            const userName = row.querySelector('.user-info span').textContent;
            const applicationTitle = row.querySelector('.application-title').textContent;
            const demandTitle = row.querySelector('.application-demand').textContent;
            
            switch (action) {
                case '查看详情':
                    showApplicationDetails(userName, applicationTitle, demandTitle, row);
                    break;
                case '通过':
                    approveApplication(userName, applicationTitle, row);
                    break;
                case '拒绝':
                    rejectApplication(userName, applicationTitle, row);
                    break;
            }
        });
    });
}

/**
 * 显示申请详情
 * @param {string} userName - 用户名
 * @param {string} applicationTitle - 申请标题
 * @param {string} demandTitle - 需求标题
 * @param {HTMLElement} row - 表格行元素
 */
function showApplicationDetails(userName, applicationTitle, demandTitle, row) {
    // 获取申请ID（这里模拟，实际应从数据库获取）
    const applicationId = row.dataset.id || Math.floor(Math.random() * 10000);
    
    // 创建模态框显示详情
    const modalHtml = `
        <div class="application-detail-modal" id="application-modal-${applicationId}">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>申请详情</h3>
                    <button class="modal-close" onclick="closeApplicationModal('application-modal-${applicationId}')">&times;</button>
                </div>
                <div class="application-detail-section">
                    <h3>基本信息</h3>
                    <div class="detail-row">
                        <div class="detail-label">申请人：</div>
                        <div class="detail-value">${userName}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">申请标题：</div>
                        <div class="detail-value">${applicationTitle}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">支教需求：</div>
                        <div class="detail-value">${demandTitle}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">申请时间：</div>
                        <div class="detail-value">2023-09-15</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">联系方式：</div>
                        <div class="detail-value">13800138000</div>
                    </div>
                </div>
                <div class="application-detail-section">
                    <h3>申请说明</h3>
                    <div class="detail-row">
                        <div class="detail-value">我是一名大学生，有丰富的支教经验，希望能够参与这个项目，为山区孩子带去知识和希望。我曾参与过两次支教活动，擅长语文和数学教学。</div>
                    </div>
                </div>
                <div class="application-detail-section">
                    <h3>教学经验</h3>
                    <div class="detail-row">
                        <div class="detail-value">2021年7月-8月：参与"希望工程"支教活动，在贵州山区小学教授语文课程。<br>2022年7月-8月：参与"阳光支教"项目，在云南山区小学教授数学课程。</div>
                    </div>
                </div>
                <div class="application-actions">
                    <button class="btn btn-primary" onclick="approveApplicationFromModal('${userName}', '${applicationTitle}', ${applicationId})">通过申请</button>
                    <button class="btn btn-danger" onclick="rejectApplicationFromModal('${userName}', '${applicationTitle}', ${applicationId})">拒绝申请</button>
                </div>
            </div>
        </div>
    `;
    
    // 添加模态框到页面
    if (!document.getElementById(`application-modal-${applicationId}`)) {
        document.body.insertAdjacentHTML('beforeend', modalHtml);
    }
    
    // 显示模态框
    setTimeout(() => {
        const modal = document.getElementById(`application-modal-${applicationId}`);
        modal.classList.add('show');
    }, 10);
}

/**
 * 关闭申请详情模态框
 * @param {string} modalId - 模态框ID
 */
function closeApplicationModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.remove('show');
    
    // 延迟移除DOM元素
    setTimeout(() => {
        modal.remove();
    }, 300);
}

/**
 * 从模态框通过申请
 * @param {string} userName - 用户名
 * @param {string} applicationTitle - 申请标题
 * @param {number} applicationId - 申请ID
 */
function approveApplicationFromModal(userName, applicationTitle, applicationId) {
    // 关闭模态框
    closeApplicationModal(`application-modal-${applicationId}`);
    
    // 查找对应的行
    let row = document.querySelector(`tr[data-id="${applicationId}"]`);
    
    // 如果通过ID找不到，则通过标题查找
    if (!row) {
        const allTitles = document.querySelectorAll('.application-title');
        for (let i = 0; i < allTitles.length; i++) {
            if (allTitles[i].textContent === applicationTitle) {
                row = allTitles[i].closest('tr');
                break;
            }
        }
    }
    
    if (row) {
        // 更新状态标识
        const statusBadge = row.querySelector('.status-badge');
        statusBadge.className = 'status-badge status-approved';
        statusBadge.textContent = '已通过';
        
        // 移除操作按钮，只保留查看详情
        const tableActions = row.querySelector('.table-actions');
        tableActions.innerHTML = `
            <button class="btn-icon" title="查看详情">
                <i class="bi bi-eye"></i>
            </button>
        `;
        
        // 重新绑定事件
        const viewButton = tableActions.querySelector('.btn-icon');
        viewButton.addEventListener('click', function() {
            const userName = row.querySelector('.user-info span').textContent;
            const applicationTitle = row.querySelector('.application-title').textContent;
            const demandTitle = row.querySelector('.application-demand').textContent;
            showApplicationDetails(userName, applicationTitle, demandTitle, row);
        });
    }
    
    // 显示成功通知
    window.utils.showNotification(`已通过 ${userName} 的申请`, 'success');
}

/**
 * 从模态框拒绝申请
 * @param {string} userName - 用户名
 * @param {string} applicationTitle - 申请标题
 * @param {number} applicationId - 申请ID
 */
function rejectApplicationFromModal(userName, applicationTitle, applicationId) {
    // 关闭模态框
    closeApplicationModal(`application-modal-${applicationId}`);
    
    // 查找对应的行
    let row = document.querySelector(`tr[data-id="${applicationId}"]`);
    
    // 如果通过ID找不到，则通过标题查找
    if (!row) {
        const allTitles = document.querySelectorAll('.application-title');
        for (let i = 0; i < allTitles.length; i++) {
            if (allTitles[i].textContent === applicationTitle) {
                row = allTitles[i].closest('tr');
                break;
            }
        }
    }
    
    if (row) {
        // 更新状态标识
        const statusBadge = row.querySelector('.status-badge');
        statusBadge.className = 'status-badge status-rejected';
        statusBadge.textContent = '已拒绝';
        
        // 移除操作按钮，只保留查看详情
        const tableActions = row.querySelector('.table-actions');
        tableActions.innerHTML = `
            <button class="btn-icon" title="查看详情">
                <i class="bi bi-eye"></i>
            </button>
        `;
        
        // 重新绑定事件
        const viewButton = tableActions.querySelector('.btn-icon');
        viewButton.addEventListener('click', function() {
            const userName = row.querySelector('.user-info span').textContent;
            const applicationTitle = row.querySelector('.application-title').textContent;
            const demandTitle = row.querySelector('.application-demand').textContent;
            showApplicationDetails(userName, applicationTitle, demandTitle, row);
        });
    }
    
    // 显示成功通知
    window.utils.showNotification(`已拒绝 ${userName} 的申请`, 'success');
}

/**
 * 通过申请
 * @param {string} userName - 用户名
 * @param {string} applicationTitle - 申请标题
 * @param {HTMLElement} row - 表格行元素
 */
function approveApplication(userName, applicationTitle, row) {
    window.utils.showConfirm(
        `确定通过 ${userName} 的申请吗？`,
        function() {
            // 更新状态标识
            const statusBadge = row.querySelector('.status-badge');
            statusBadge.className = 'status-badge status-approved';
            statusBadge.textContent = '已通过';
            
            // 移除操作按钮，只保留查看详情
            const tableActions = row.querySelector('.table-actions');
            tableActions.innerHTML = `
                <button class="btn-icon" title="查看详情">
                    <i class="bi bi-eye"></i>
                </button>
            `;
            
            // 重新绑定事件
            const viewButton = tableActions.querySelector('.btn-icon');
            viewButton.addEventListener('click', function() {
                const userName = row.querySelector('.user-info span').textContent;
                const applicationTitle = row.querySelector('.application-title').textContent;
                const demandTitle = row.querySelector('.application-demand').textContent;
                showApplicationDetails(userName, applicationTitle, demandTitle, row);
            });
            
            // 显示成功通知
            window.utils.showNotification(`已通过 ${userName} 的申请`, 'success');
        }
    );
}

/**
 * 拒绝申请
 * @param {string} userName - 用户名
 * @param {string} applicationTitle - 申请标题
 * @param {HTMLElement} row - 表格行元素
 */
function rejectApplication(userName, applicationTitle, row) {
    window.utils.showConfirm(
        `确定拒绝 ${userName} 的申请吗？`,
        function() {
            // 更新状态标识
            const statusBadge = row.querySelector('.status-badge');
            statusBadge.className = 'status-badge status-rejected';
            statusBadge.textContent = '已拒绝';
            
            // 移除操作按钮，只保留查看详情
            const tableActions = row.querySelector('.table-actions');
            tableActions.innerHTML = `
                <button class="btn-icon" title="查看详情">
                    <i class="bi bi-eye"></i>
                </button>
            `;
            
            // 重新绑定事件
            const viewButton = tableActions.querySelector('.btn-icon');
            viewButton.addEventListener('click', function() {
                const userName = row.querySelector('.user-info span').textContent;
                const applicationTitle = row.querySelector('.application-title').textContent;
                const demandTitle = row.querySelector('.application-demand').textContent;
                showApplicationDetails(userName, applicationTitle, demandTitle, row);
            });
            
            // 显示成功通知
            window.utils.showNotification(`已拒绝 ${userName} 的申请`, 'success');
        }
    );
}

/**
 * 初始化分页功能
 */
function initPagination() {
    const pageItems = document.querySelectorAll('.page-item');
    pageItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有分页项的active类
            pageItems.forEach(p => p.classList.remove('active'));
            
            // 给当前分页项添加active类
            this.classList.add('active');
            
            // 加载对应页面的数据
            // 这里只是模拟，实际应该从服务器加载数据
            simulatePageChange();
        });
    });
}

/**
 * 模拟页面切换效果
 */
function simulatePageChange() {
    // 显示加载动画
    const tableContainer = document.querySelector('.application-table-container');
    tableContainer.innerHTML = '<div class="spinner" style="margin: 50px auto;"></div>';
    
    // 模拟加载延迟
    setTimeout(() => {
        // 恢复表格内容（实际应该是加载新数据）
        tableContainer.innerHTML = document.querySelector('.application-table-container').dataset.originalContent || tableContainer.innerHTML;
        
        // 重新绑定表格事件
        initTableActions();
    }, 500);
}

/**
 * 导出申请数据
 */
function exportApplicationData() {
    // 获取表格数据
    const applications = [];
    const rows = document.querySelectorAll('.admin-table tbody tr');
    
    rows.forEach(row => {
        // 只导出可见行
        if (row.style.display !== 'none') {
            const userName = row.querySelector('.user-info span').textContent;
            const applicationTitle = row.querySelector('.application-title').textContent;
            const demandInfo = row.querySelector('.application-demand').textContent;
            const date = row.querySelector('td:nth-child(4)').textContent;
            const status = row.querySelector('.status-badge').textContent;
            
            applications.push({
                applicant: userName,
                title: applicationTitle,
                demand: demandInfo,
                date: date,
                status: status
            });
        }
    });
    
    // 转换为CSV格式
    let csv = 'applicant,title,demand,date,status\n';
    applications.forEach(app => {
        csv += `"${app.applicant}","${app.title}","${app.demand}","${app.date}","${app.status}"\n`;
    });
    
    // 创建下载链接
    const dataUri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    const exportFileDefaultName = 'applications.csv';
    
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
    
    // 显示导出成功提示
    window.utils.showNotification('申请数据已导出', 'success');
}

// 绑定导出按钮事件
document.addEventListener('DOMContentLoaded', function() {
    // 使用更兼容的方式查找带有下载图标的按钮
    const buttons = document.querySelectorAll('.btn-primary');
    let exportButton = null;
    
    // 遍历所有主要按钮，查找包含下载图标的按钮
    for (let i = 0; i < buttons.length; i++) {
        if (buttons[i].querySelector('i.bi-download')) {
            exportButton = buttons[i];
            break;
        }
    }
    
    if (exportButton) {
        exportButton.addEventListener('click', exportApplicationData);
    }
});

/**
 * 初始化批量操作
 */
function initBatchOperations() {
    // 全选功能
    const selectAllCheckbox = document.getElementById('select-all-applications');
    const applicationCheckboxes = document.querySelectorAll('.application-checkbox');
    
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            applicationCheckboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }
    
    // 批量操作按钮可以在这里添加
    // 例如批量通过、批量拒绝等
}

/**
 * 更新分页
 */
function updatePagination() {
    // 获取可见行数
    const visibleRows = document.querySelectorAll('.admin-table tbody tr:not([style*="display: none"])');
    
    // 如果没有可见行，显示无数据提示
    if (visibleRows.length === 0) {
        const tableBody = document.querySelector('.admin-table tbody');
        if (!tableBody.querySelector('.no-data-row')) {
            const noDataRow = document.createElement('tr');
            noDataRow.className = 'no-data-row';
            noDataRow.innerHTML = '<td colspan="7" style="text-align: center; padding: 20px;">没有找到匹配的申请记录</td>';
            tableBody.appendChild(noDataRow);
        }
    } else {
        // 移除无数据提示
        const noDataRow = document.querySelector('.no-data-row');
        if (noDataRow) {
            noDataRow.remove();
        }
    }
}

// 添加全局函数，用于从HTML调用
window.closeApplicationModal = closeApplicationModal;
window.approveApplicationFromModal = approveApplicationFromModal;
window.rejectApplicationFromModal = rejectApplicationFromModal;